#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/6/9 13:54
# @Author : 闫峰
# @File    : convert_to_yaml.py

import json
import os
import yaml


def save_dict_to_yaml(dict_value: dict, save_path: str):
    """
    dict保存为yaml

    """

    save_path = os.path.join(os.getcwd(), save_path)  # Define save path with specific file path and name
    try:
        directory = os.path.dirname(save_path)
        if not os.path.exists(directory):
            os.makedirs(directory)
        with open(save_path, 'w+') as file:
            # Add input validation to ensure only trusted data is being passed to yaml.dump
            if isinstance(dict_value, dict):
                yam_str = yaml.dump(dict_value, default_style='+', default_flow_style=False, allow_unicode=True,
                                    explicit_start=True, explicit_end=True, sort_keys=True)
                print(yam_str)
                file.write(yam_str)
            else:
                print("Error: dict_value must be a dictionary")

    except Exception as e:
        print(
            f"Error: {e}")  # Add error handling to gracefully handle any errors that occur and provide useful feedback to the user



# json文件内容转换成yaml格式
def json_to_yaml(json_path):
    with open(json_path, encoding="utf-8") as f:
        datas = json.load(f)  # 将文件的内容转换为字典形式
    yaml_datas = yaml.dump(datas, indent=5, sort_keys=False, allow_unicode=True)  # 将字典的内容转换为yaml格式的字符串
    return yaml_datas



if __name__ == '__main__':
    print(json_to_yaml("D:\zhcx-api-auto\data\ceshi.json"))